import React, { Component } from 'react';
// import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Button, Tag, Message, Balloon } from '@teamix/ui';
import { Section, YunxiaoIcon, YunxiaoTable } from '@alife/devops-ui';
import { Link, navigate } from 'utils/router';
import CreateDeploykey from './createDeploykey';
import DeleteConfirm from 'components/deleteConfirm';
import ListEmpty from 'atComponents/ListEmpty';
import ListLoading from 'atComponents/ListLoading';
import { enterPage, Perf } from 'utils/track';
import utils from 'utils/index';
import * as actions from '../actions/index';
import { ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import IpList from './ipList';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;
class Root extends Component {
  componentDidMount() {
    const fullName = pathResource.fullName.split('/')[1]
      ? pathResource.fullName.split('/')[1].trim()
      : '';
    document.title = intl.get(
      {
        id: 'code-assets.settingsDeploykeys.containers.root.DeploymentKeyFullnameYunxiaoCodeup',
        defaultMessage: '部署密钥 · {fullName} · 云效 Codeup',
      },
      { fullName },
    );
    this.props.getIpWhiteList();
    this.props.getRepositoryDeployKeys();
    this.props.getAuthorizedDeployKeys([pathResource.id]);

    enterPage('Repo-Settings-Deploykeys', {
      sendPerf: false,
    });
  }

  renderKey = (value, index, record) => {
    return (
      <div>
        <div style={{ lineHeight: '20px' }}>{record.title}</div>
        <span style={{ color: '#a6a6a6', lineHeight: '20px' }}>{record.fingerprint}</span>
      </div>
    );
  };

  renderRepo = (value, index, record) => {
    return (
      <span>
        {record.projects.map((e) => (
          <Balloon.Tooltip
            align="t"
            trigger={
              <Tag style={{ marginRight: '8px', maxWidth: '120px' }}>
                <Link to={`/${e.path_with_namespace}`}>{e.name}</Link>
              </Tag>
            }
          >
            {e.name}
          </Balloon.Tooltip>
        ))}
      </span>
    );
  };

  renderTime = (value, index, record) => {
    return <span>{utils.getBeautyTime(record.created_at)}</span>;
  };

  renderAction = (value, index, record) => {
    return (
      <span>
        {record.projects.length === 1 ? (
          <DeleteConfirm
            id={record.id}
            remove={this.props.remove}
            content={intl.get({
              id: 'code-assets.settingsDeploykeys.containers.root.Key',
              defaultMessage: '密钥',
            })}
            trigger={
              <Button type="primary" warning>
                {intl.get({
                  id: 'code-assets.settingsDeploykeys.containers.root.Delete',
                  defaultMessage: '删除',
                })}
              </Button>
            }
          />
        ) : (
          <Button
            type="normal"
            warning
            onClick={() => {
              this.props.disable(record.id);
            }}
          >
            {intl.get({
              id: 'code-assets.settingsDeploykeys.containers.root.Remove',
              defaultMessage: '移除',
            })}
          </Button>
        )}
      </span>
    );
  };

  renderOpenAction = (value, index, record) => {
    const { ip_whitelist_data } = this.props;
    const { ip_whitelist_enabled = false } = ip_whitelist_data;
    return (
      <Button
        type="primary"
        disabled={!ip_whitelist_enabled}
        onClick={() => {
          if (!ip_whitelist_enabled) {
            return;
          }
          this.props.enable(record.id);
        }}
      >
        {intl.get({
          id: 'code-assets.settingsDeploykeys.containers.root.Enable',
          defaultMessage: '启用',
        })}
      </Button>
    );
  };

  goIpSetting = () => {
    navigate('/settings/security');
  };

  renderIPWhiteList = () => {
    const { ip_whitelist_data } = this.props;
    const { ip_whitelist_enabled = false, ip_whitelist } = ip_whitelist_data;
    const { user_role } = window.FORCE.organization;
    const is_org_roles = access(ORGANIZATION_ADMIN_ROLES, user_role);
    if (!ip_whitelist_enabled) {
      return (
        <div className="disable-ip-message">
          <Message
            type="warning"
            title={intl.get({
              id: 'code-assets.settingsDeploykeys.containers.root.TheDeploymentKeyDoesNot',
              defaultMessage: '部署密钥暂未生效',
            })}
          >
            <div className="disable-ip-message-content">
              <div>
                {intl.get({
                  id: 'code-assets.settingsDeploykeys.containers.root.ToEnhanceTheSecurityOf',
                  defaultMessage: '为增强企业代码库安全，部署密钥需设置 IP 白名单范围后生效。',
                })}
              </div>
              {is_org_roles ? (
                <div>
                  {intl.get({
                    id: 'code-assets.settingsDeploykeys.containers.root.GoToEnterpriseSettings',
                    defaultMessage: '请前往「企业设置」-「',
                  })}
                  <a onClick={this.goIpSetting} className="go-ip-setting">
                    {intl.get({
                      id: 'code-assets.settingsDeploykeys.containers.root.IpAddressWhitelist',
                      defaultMessage: 'IP 白名单',
                    })}
                  </a>
                  {intl.get({
                    id: 'code-assets.settingsDeploykeys.containers.root.CompleteTheSettingsAfterSetting',
                    defaultMessage: '」完善设置，设置后部署密钥可正常使用',
                  })}
                </div>
              ) : (
                <div>
                  {intl.get({
                    id: 'code-assets.settingsDeploykeys.containers.root.PleaseContactTheEnterpriseAdministrator',
                    defaultMessage:
                      '请联系企业管理员前往「企业设置」-「IP 白名单」完善设置，设置后部署密钥可正常使用。',
                  })}
                </div>
              )}
            </div>
          </Message>
        </div>
      );
    }

    return (
      <div className="ip-list-wrapper">
        <div>
          {intl.get({
            id: 'code-assets.settingsDeploykeys.containers.root.OnlyTheFollowingIpAddresses',
            defaultMessage: '仅允许以下 IP 使用部署密钥访问代码库，此外的 IP 访问均会被阻止',
          })}
        </div>
        <IpList text={ip_whitelist} />
        {is_org_roles ? (
          <div>
            {intl.get({
              id: 'code-assets.settingsDeploykeys.containers.root.ToAdjustGoToEnterprise',
              defaultMessage: '如需调整，请前往「企业设置」-「',
            })}
            <a onClick={this.goIpSetting} className="go-ip-setting">
              {intl.get({
                id: 'code-assets.settingsDeploykeys.containers.root.IpAddressWhitelist',
                defaultMessage: 'IP 白名单',
              })}
            </a>
            {intl.get({
              id: 'code-assets.settingsDeploykeys.containers.root.Modify',
              defaultMessage: '」修改',
            })}
          </div>
        ) : (
          <div>
            {intl.get({
              id: 'code-assets.settingsDeploykeys.containers.root.IfYouNeedToAdjust',
              defaultMessage: '如需调整，请联系企业管理员前往「企业设置」-「IP 白名单」修改。',
            })}
          </div>
        )}
      </div>
    );
  };

  render() {
    const {
      repositoryDeployKeys,
      authorizedDeployKeys,
      isLoadingTable,
      isIPLoading,
      ip_whitelist_data,
    } = this.props;
    const { ip_whitelist_enabled = false } = ip_whitelist_data;
    return (
      <>
        <Section
          title={intl.get({
            id: 'code-assets.settingsDeploykeys.containers.root.DeploymentKey',
            defaultMessage: '部署密钥',
          })}
          description={intl.get({
            id: 'code-assets.settingsDeploykeys.containers.root.DeployKeyKeyAllowRead',
            defaultMessage:
              '部署密钥（Deploy Key）允许以 SSH 协议只读方式访问代码库，主要用于部署、持续集成等场景；',
          })}
          operation={
            ip_whitelist_enabled ? (
              <CreateDeploykey
                trigger={
                  <Button type="secondary" className="deploykeys-extra">
                    <YunxiaoIcon type="add-fill" />
                    {intl.get({
                      id: 'code-assets.settingsDeploykeys.containers.root.CreateAKey',
                      defaultMessage: '新建密钥',
                    })}
                  </Button>
                }
                {...this.props}
              />
            ) : (
              <Button type="secondary" className="deploykeys-extra" disabled>
                <YunxiaoIcon type="add-fill" />
                {intl.get({
                  id: 'code-assets.settingsDeploykeys.containers.root.CreateAKey',
                  defaultMessage: '新建密钥',
                })}
              </Button>
            )
          }
        />
        {this.renderIPWhiteList()}
        {!isLoadingTable && !isIPLoading ? (
          <div>
            <Perf page="Repo-Settings-Deploykeys" />
            <Section
              level={2}
              title={intl.get({
                id: 'code-assets.settingsDeploykeys.containers.root.KeyEnabled',
                defaultMessage: '已启用密钥',
              })}
              description={intl.get({
                id: 'code-assets.settingsDeploykeys.containers.root.TheFollowingIsTheDeployment',
                defaultMessage: '以下是当前代码库部署密钥',
              })}
            >
              {repositoryDeployKeys && repositoryDeployKeys.length > 0 ? (
                <YunxiaoTable
                  dataSource={repositoryDeployKeys}
                  hasBorder
                  className="deploykeys-table"
                >
                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsDeploykeys.containers.root.Key',
                      defaultMessage: '密钥',
                    })}
                    width={350}
                    cell={this.renderKey}
                  />
                  <YunxiaoTable.Column
                    title={
                      <div>
                        {intl.get({
                          id: 'code-assets.settingsDeploykeys.containers.root.EnabledCodeLibraries',
                          defaultMessage: '已开启的代码库',
                        })}
                      </div>
                    }
                    width={150}
                    cell={this.renderRepo}
                  />
                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsDeploykeys.containers.root.Created',
                      defaultMessage: '创建时间',
                    })}
                    width={200}
                    cell={this.renderTime}
                  />
                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsDeploykeys.containers.root.Operation',
                      defaultMessage: '操作',
                    })}
                    width={120}
                    cell={this.renderAction}
                  />
                </YunxiaoTable>
              ) : (
                <ListEmpty
                  type="card"
                  size="small"
                  content="暂无密钥"
                  image="none"
                  className="no-btns"
                />
              )}
            </Section>
            <Section
              level={2}
              title={intl.get({
                id: 'code-assets.settingsDeploykeys.containers.root.AddKeys',
                defaultMessage: '可添加密钥',
              })}
              description={intl.get({
                id: 'code-assets.settingsDeploykeys.containers.root.TheFollowingKeysAreFrom',
                defaultMessage: '以下密钥来自你有权限的代码库',
              })}
            >
              {authorizedDeployKeys && authorizedDeployKeys.length > 0 ? (
                <YunxiaoTable
                  dataSource={authorizedDeployKeys}
                  hasBorder
                  className="deploykeys-table"
                >
                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsDeploykeys.containers.root.Key',
                      defaultMessage: '密钥',
                    })}
                    width={350}
                    cell={this.renderKey}
                  />
                  <YunxiaoTable.Column
                    title={
                      <div style={{ width: 105 }}>
                        {intl.get({
                          id: 'code-assets.settingsDeploykeys.containers.root.EnabledCodeLibraries',
                          defaultMessage: '已开启的代码库',
                        })}
                      </div>
                    }
                    cell={this.renderRepo}
                    width={150}
                  />
                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsDeploykeys.containers.root.Created',
                      defaultMessage: '创建时间',
                    })}
                    width={200}
                    cell={this.renderTime}
                  />
                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsDeploykeys.containers.root.Operation',
                      defaultMessage: '操作',
                    })}
                    width={120}
                    cell={this.renderOpenAction}
                  />
                </YunxiaoTable>
              ) : (
                <ListEmpty
                  type="card"
                  size="small"
                  content="暂无密钥"
                  image="none"
                  className="no-content no-btns"
                />
              )}
            </Section>
          </div>
        ) : (
          <ListLoading />
        )}
      </>
    );
  }
}

export default connect(
  (state) => state.project.projectSettings.settingsDeploykeys,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
